
from flask import request
from flask_socketio import SocketIO, emit, join_room, leave_room
from utils.randomUtils import generate_random_token, generate_random_by_time
import threading
from .baseGraphNode import BaseGraphNode
from .httpGraphNode import HttpGraphNode
from .sessionInfo import SessionInfo

class HttpInGraphNode(BaseGraphNode):
    def __init__(self, id:str, data:dict, graphNodeManager, random_key:str):
        super().__init__(id, data, graphNodeManager, random_key)
        self.route = data['data']['route']
        self.enWS = data['data']['enWS']
        self.enInterrupt = data['data']['enInterrupt']
        if self.graphNodeManager.http_node is not None:
            self.full_url = self.graphNodeManager.http_node.full_url
        else:
            self.graphNodeManager.http_node = HttpGraphNode(generate_random_by_time(), self.data, self.graphNodeManager, self.random_key)
            self.full_url = self.graphNodeManager.http_node.full_url
        self._ws_token = self.full_url
        self.running = False

    def execute(self, session_info: SessionInfo=None):
        if (not self.running):
            if self.route in self.graphNodeManager.project.onlineRoutes:
                self.graphNodeManager.project.onlineRoutes.pop(self.route)
            self.running = True
            
            socketio_instance = self.graphNodeManager.http_node.get_socketio_instance()
            def create_websocket_route(route, full_url):
                @socketio_instance.on('connect', namespace=full_url)
                def on_connect():
                    print(f"WebSocket connected on route: {full_url} User sid:{request.sid}")
                    emit('response', {'data': 'Connected to WebSocket!'})

                @socketio_instance.on(route, namespace=full_url)
                def handle_message(msg):
                    sid = request.sid
                    print(f'Received message: {msg}, sid:{sid}')
                    sessionInfo = self.graphNodeManager.sid_to_sessionInfo.get(sid, None) 
                    if sessionInfo is None: 
                        sessionInfo = self.graphNodeManager.createSessionInfo(generate_random_by_time(),socketio_instance, sid, route, full_url)
                        join_room(sid)  
                    if sessionInfo.id not in self.dict['out']: self.dict['out'][sessionInfo.id] = {}
                    if 'query-msg' not in self.dict['out'][sessionInfo.id] : self.dict['out'][sessionInfo.id]['query-msg'] = []
                    self.dict['out'][sessionInfo.id]['query-msg'].append(msg)
                    self.executed_num += 1
                    self.flow_next(sessionInfo)
                    
                @socketio_instance.on('disconnect', namespace=full_url)
                def on_disconnect():
                    sid = request.sid
                    print(f"WebSocket disconnected on route: {full_url} User sid: {sid}")
                    leave_room(sid)  # 将客户端从

            # 启动新的 SocketIO 实例在指定的端口上监听
            threading.Thread(target=create_websocket_route, args=(self.route, self.full_url)).start()
            self.graphNodeManager.project.addOnlineRoute(self.route, 'message', self.name)
            print(f'WebSocket app created and listening, route: {self.full_url}')

    
